﻿using System;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Collections.Generic;

namespace ImaginaryDevelopmentMvc3.App.Auth
{
    /// <summary>
    /// http://msdn.microsoft.com/en-us/library/hh243648.aspx#user
    /// </summary>
    [DataContract]
    public class WindowsLiveUser
    {
        private static DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(WindowsLiveUser));

        [DataMember(Name = "id")]
        public string ID { get; set; }

        [DataMember(Name = "name")]
        public string Name { get; set; }
        [DataMember(Name = "first_name")]
        public string FirstName { get; set; }
        [DataMember(Name = "last_name")]
        public string LastName { get; set; }
        [DataMember(Name = "gender")]
        public string Gender { get; set; }
        [DataMember(Name = "locale")]
        public string Locale { get; set; }

        public ILookup<string, object> Data { get; set; }

        /// <summary>
        /// Serialize using JsonSerializer
        /// </summary>
        /// <returns></returns>
        public string ToJson()
        {
            System.Diagnostics.Contracts.Contract.Result<string>().IsNotNullOrEmpty();
            using (var writer = new MemoryStream())
            {
                Contract.Ensures(Contract.Result<string>() != null);
                jsonSerializer.WriteObject(writer, this);
                using (var reader = new StreamReader(writer))

                    return reader.ReadToEnd();
            }
        }

        public static WindowsLiveUser Deserialize(string json)
        {
            if (String.IsNullOrEmpty(json))
            {
                throw new ArgumentNullException("json");
            }

            return Deserialize(new MemoryStream(Encoding.UTF8.GetBytes(json)));
        }

        public static WindowsLiveUser Deserialize(Stream jsonStream)
        {

            if (jsonStream == null)
            {
                throw new ArgumentNullException("jsonStream");
            }
            var obj = jsonSerializer.ReadObject(jsonStream);

            WindowsLiveUser wl = (WindowsLiveUser)obj;
            var dic = (Dictionary<string, object>)obj;
            if(dic!=null)
            wl.Data = dic.ToLookup(kvp=>kvp.Key,kvp=>kvp.Value);

            return wl;
        }

    }
}